package com.ruoyi.system.service;

import com.google.common.util.concurrent.RateLimiter;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class RateLimiterService {

    @Autowired
    private RedisCache redisCache;

    /**
     * 每秒只发出10个令牌
     */
    RateLimiter rateLimiter = RateLimiter.create(10.0);

    private ConcurrentHashMap<String,RateLimiter> rateLimiterMap = new ConcurrentHashMap();

    private final String RATELIMITER_KEY = "KEYS_RATE_LIMITER";

    /**
     * 尝试获取令牌
     * @return
     */
    public boolean tryAcquire(){
        // todo 按接口区分 ：1。接口每秒响应多少 ；2. 接口对于特定人员限定多少 3.接口对单个人限定每秒多少
        // 这个就是针对接口的
        return rateLimiter.tryAcquire();
    }

    public boolean tryAcquire(String uri,Integer times){
        RateLimiter rateLimiter = rateLimiterMap.get(uri);
        if (rateLimiter != null){
            return rateLimiter.tryAcquire();
        }
        rateLimiter = RateLimiter.create(times);
        rateLimiterMap.put(uri,rateLimiter);
        return this.rateLimiter.tryAcquire();
    }

}